import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/views/Login'
import NotFound from '@/views/Error/404'
import Home from '@/views/Home'
import Intro from '@/views/Intro/Intro'
import api from '@/http/api'
import axios from 'axios'
import store from '@/store'
import { getIFrameUrl } from '@/utils/iframe'
import NewMessage from '@/views/MessageManagement/NewMessage'
import PublicMessage from '@/views/MessageManagement/PublicMessage'
import Cookies from "js-cookie";
import Student from '@/views/Customerfile/Student'
import AddStudent from '@/views/Customerfile/AddStudent'
import Schoolfile from '@/views/Customerfile/School'
import StudentFollow from '@/views/Follow/StudentFollow'
import SchoolFollow from '@/views/Follow/SchoolFollow'
import AddSchool from '@/views/Customerfile/AddSchool'
import ChinaeduAgent from '@/views/Customerfile/ChinaeduAgent'
import XuecooAgent from '@/views/Customerfile/XuecooAgent'
import AgentFollow from '@/views/Follow/AgentFollow'
import XuecooFollow from '@/views/Follow/XuecooFollow'
import AddChinaedu from '@/views/Customerfile/AddChinaedu'
import AddXuecoo from '@/views/Customerfile/AddXuecoo'
import EditStudent from '@/views/Customerfile/EditStudent'
import AddMyStudent from '@/views/Customerfile/AddMyStudent'
import notFound from '@/views/Error/404'
import EditXuecoo from '@/views/Customerfile/EditXuecoo'
import EditChinaedu from '@/views/Customerfile/EditChinaedu'
import EditSchool from '@/views/Customerfile/EditSchool'
import MobileLogin from '@/views/MobileLogin'
import MobileIndex from '@/views/Mobile/index'
import MobileMycustomerChinaedu from '@/views/Mobile/Mycustomer/Chinaedu'
import MobileMycustomerXuecoo from '@/views/Mobile/Mycustomer/Xuecoo'
import MobileDirectCampCenterMySchool  from '@/views/Mobile/DirectCampCenter/MySchool'
import MobileCustomerInfo from '@/views/Mobile/CustomerInfo/CustomerInfo'
import MobileIntro from '@/views/Mobile/MobileIntro/MobileIntro'
import MobileCustomerTracking from'@/views/Mobile/Tracking/Tracking'
import MobileAddCustomer from'@/views/Mobile/CustomerInfo/AddCustomer'
import MobileTrackingInfo from'@/views/Mobile/Tracking/TrackingInfo'
import MobileNameRepeat from'@/views/Mobile/DirectCampCenter/NameRepeat'
import DictionaryData from'@/views/SystemManage/DictionaryData'
import MobileMycustomerChinaeduOrder from'@/views/Mobile/Mycustomer/ChinaeduOrder'
import MobileMycustomerXuecooOrder from'@/views//Mobile/Mycustomer/XuecooOrder'
import MarketingCalendarFile from'@/views/MarketingManage/MarketingCalendarFile'
import MarketingCalendarConfig from'@/views/MarketingManage/MarketingCalendarConfig'
import MaterialPackage from'@/views/MarketingManage/MaterialPackage'
import MarketingCalendar from'@/views/MarketingCalendar/MarketingCalendar'
import AnswerDetails from'@/views/Answer/AnswerDetails'
import PosterDetail from'@/views/Customerfile/PosterDetail'
import ThreeFile from'@/views/Customerfile/ThreeFile'
import ThreeFileBase from'@/views/Customerfile/ThreeFileBase'
import StudentStatisticsDaysInfo from'@/views/Customerstatistics/StudentStatisticsDaysInfo'
import RecycleDetailList from '@/views/ResourceMonitoring/RecycleDetailList'
import OrderListInfo from '@/views/OrderInfoMange/OrderListInfo'


import { baseUrl } from '../utils/global'

const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}
Vue.use(Router)

const router = new Router({ 
  routes: [
    {
      path: '/',
      name: '首页',
      component: Home,
      meta:{auth:true},
      children: [
        {
          path: '',
          name: '101crm系统',
          component: Intro
        },
        {
          path: '/Customerfile/Student',
          name: '查看学生客户',
          component: Student
        },
        {
          path: '/MessageManagement/NewMessage',
          name: '新增消息公告',
          component: NewMessage
        },
        {
          path: '/MessageManagement/PublicMessage',
          name: '我的消息',
          component: PublicMessage
        },
        {
          path: '/Follow/StudentFollow',
          name: '学生客户跟进表',
          component: StudentFollow
        },
        {
          path: '/Follow/SchoolFollow',
          name: '学校客户跟进表',
          component: SchoolFollow
        },
        {
          path: '/Follow/XuecooFollow',
          name: '学酷客户跟进表',
          component: XuecooFollow
        },
        {
          path: '/Follow/AgentFollow',
          name: '代理商客户跟进表',
          component: AgentFollow
        },
        {
          path: '/Customerfile/AddStudent',
          name: '新增学生客户',
          component: AddStudent
        },
        {
          path: '/Customerfile/AddMyStudent',
          name: '新增我的客户',
          component: AddMyStudent
        },
        {
          path: '/Customerfile/EditStudent',
          name: '修改学生客户',
          component: EditStudent,
        },
        {
          path: '/Customerfile/EditSchool',
          name: '修改学校客户',
          component: EditSchool
        },
        {
          path: '/Customerfile/EditXuecoo',
          name: '修改学酷代理商客户',
          component: EditXuecoo
        },
        {
          path: '/Customerfile/EditChinaedu',
          name: '修改网校代理商客户',
          component: EditChinaedu
        },
        {
          path: '/Customerfile/AddXuecoo',
          name: '学酷代理商新增客户',
          component: AddXuecoo
        },
        {
          path: '/Customerfile/AddChinaedu',
          name: '网校代理商新增客户',
          component: AddChinaedu
        },
        {
          path: '/Customerfile/ChinaeduAgent',
          name: '网校/代理商客户',
          component: ChinaeduAgent
        },
        {
          path: '/Customerfile/XuecooAgent',
          name: '学酷/代理商客户',
          component: XuecooAgent
        },
        {
          path: '/Customerfile/AddSchool',
          name: '新增学校客户',
          component: AddSchool
        },
        {
          path: '/Customerfile/School',
          name: '查看学校客户',
          component: Schoolfile
        },     
        
        {
          path: '/MarketingManage/MarketingCalendarConfig',
          name: '日历配置',
          component: MarketingCalendarConfig
        },
        {
          path: '/MarketingManage/MarketingCalendarFile',
          name: '查看日历',
          component: MarketingCalendarFile
        },
        {
          path: '/SystemManage/DictionaryData',
          name: '查看数据字典',
          component: DictionaryData
        },
        {
          path: '/MarketingManage/MaterialPackage',
          name: '文件管理',
          component: MaterialPackage
        },
        {
          path: '/MarketingCalendar/MarketingCalendar',
          name: '日历预览',
          component: MarketingCalendar
        },
        {
          path: '/Answer/AnswerDetails',
          name: '问卷详情',
          component: AnswerDetails
        },
        {
          path: '/Customerfile/PosterDetail',
          name: '海报预览',
          component: PosterDetail
        },
        {
          path: '/Customerfile/ThreeFile',
          name: '添加三方',
          component: ThreeFile
        },
        {
          path: '/Customerfile/ThreeFileBase',
          name: '三方基本信息',
          component: ThreeFileBase
        },
        {
          path: '/Customerstatistics/StudentStatisticsDaysInfo',
          name: '资源咨询日报统计详情',
          component: StudentStatisticsDaysInfo
        },
        {
          path: '/ResourceMonitoring/RecycleDetailList',
          name: '未跟进资源统计表',
          component: RecycleDetailList
        },
        {
          path: '/OrderInfoMange/OrderListInfo',
          name: '订单详情',
          component: OrderListInfo
        },
        
      ]
    },
    {
      path: '/login',
      name: '登录',
      component: Login
    },
    {
      path: '/MobileIndex',
      name: '移动端首页',
      component: MobileIndex,
      children:[
        {
          path: '/MobileIntro',
          name: '101移动端crm系统',
          component:MobileIntro
        },
        {
          path: '/Mobile/Mycustomer/Chinaedu',
          name: '代理商移动端',
          component: MobileMycustomerChinaedu
        },
        {
          path: '/Mobile/Mycustomer/Xuecoo',
          name: '代理商移动端',
          component: MobileMycustomerXuecoo
        },
        {
          path: '/Mobile/Mycustomer/ChinaeduOrder',
          name: '代理商移动端',
          component: MobileMycustomerChinaeduOrder
        },
        {
          path: '/Mobile/Mycustomer/XuecooOrder',
          name: '代理商移动端',
          component: MobileMycustomerXuecooOrder
        },
        {
          path: '/Mobile/DirectCampCenter/MySchool',
          name: '学校客户移动端',
          component: MobileDirectCampCenterMySchool
        },
        {
          path: '/Mobile/CustomerInfo/CustomerInfo',
          name: '查看客户',
          component: MobileCustomerInfo
        },
        {
          path: '/Mobile/Tracking/Tracking',
          name: '添加跟进',
          component: MobileCustomerTracking
        },
        {
          path: '/Mobile/CustomerInfo/AddCustomer',
          name: '新增用户',
          component: MobileAddCustomer
        },
        {
          path: '/Mobile/Tracking/TrackingInfo',
          name: '查看跟进情况',
          component: MobileTrackingInfo
        },
        {
          path: '/Mobile/DirectCampCenter/NameRepeat',
          name: '学校名称查重（移动端）',
          component: MobileNameRepeat
        }
      ]
    },
    
    {
      path: '/MobileLogin',
      name: '移动端登录',
      component: MobileLogin
    },
    
    {
      path: '/404',
      name: 'notFound',
      component: notFound
    },
  ]
})

router.beforeEach((to, from, next) => {
  // 登录界面登录成功之后，会把用户信息保存在会话
  // 存在时间为会话生命周期，页面关闭即失效。
  // let userName = localStorage.getItem('user')
  let userName = Cookies.get('webuser')
  let ismobile = localStorage.getItem('ismobile');
  if(ismobile == null){
    let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
    ismobile = flag ? 1 : 0
    //0 PC 1 手机
  }
  //  PC
     // let userName = localStorage.getItem('user')
    if (to.path === '/login') {
      // 如果是访问登录界面，如果用户会话信息存在，代表已登录过，跳转到主页
      if(userName) {
        next({ path: '/' })
      } else {
        next()
      }
    } else {
      if (!userName) {
        // 如果访问非登录界面，且户会话信息不存在，代表未登录，则跳转到登录界面
        next({ path: '/login' })
      } else {
        // 加载动态菜单和路由
        addDynamicMenuAndRoutes(userName, to, from) //PC的动态路由表
        next()
      }
    }
  
  
  // 手机
  // if (ismobile ==  1) {
  //   if (to.path === '/MobileLogin') {
  //     // 如果是访问登录界面，如果用户会话信息存在，代表已登录过，跳转到主页
  //     if(userName) {
  //       next({ path: '/MobileIntro' })
  //     } else {
  //       next()
  //     }
  //   } else {
  //     if (!userName) {
  //       // 如果访问非登录界面，且户会话信息不存在，代表未登录，则跳转到登录界面
  //       next({ path: '/MobileLogin' })
  //     } else {
  //       // 加载动态菜单和路由
  //       addDynamicMenuAndRoutes(userName, to, from)
  //       next()
  //     }
  //   }
  // }
})

// router.beforeEach((to,from,next) => {

//   if(to.matched.some( m => m.meta.auth)){

//   // 对路由进行验证
//   if(store.state.isLogin=='1') { // 已经登陆
//   next({ path: '/' })   // 正常跳转到你设置好的页面
//   }
//   else{

//   // 未登录则跳转到登陆界面，query:{ Rurl: to.fullPath}表示把当前路由信息传递过去方便登录后跳转回来；

//   　　 　　　　next({path:'/login',query:{ Rurl: to.fullPath} })
//    　　　　　}
//   　　　　}else{
//   　　　　　　next()
//   　　}
//   })
/**
* 加载动态菜单和路由
*/
function addDynamicMenuAndRoutes(userName, to, from) {

  // 保存iframeUrl到store，供IFrame组件读取展示
  store.commit('setIFrameUrl', to.path)
  if(store.state.app.menuRouteLoaded) {
    // console.log('动态菜单和路由已经存在.')
    return
  }
  api.menu.findNavTree({"authType":1,"userName":userName})
  .then(res => {
    // 添加动态路由
    let dynamicRoutes = addDynamicRoutes(res.authorityList)
    // console.log(res.authorityList)
    let aa=[]
    res.authorityList.map(item=>{
      if(item.menuName.indexOf('移动端')<0){
        aa.push(item)
      }
    })
    router.options.routes[0].children = router.options.routes[0].children.concat(dynamicRoutes)
    // console.log(router.options.routes)
    router.addRoutes(router.options.routes)
    // 保存加载状态
    store.commit('menuRouteLoaded', true)
    // 保存菜单树
    store.commit('setNavTree', aa)
  }).then(res => {
    api.menu.findLevenBtn({"authType":2})
    .then(res => {
      let perm=res.authorityList
      let perms=[]
      if(perm){
        perm.forEach(item =>{
          perms.push(item.commonButton)
        })
        // 保存用户权限标识集合
        store.commit('setPerms',perms)
      }
    })
  })
  .catch(function(res) {
  })
}

/**
* 添加动态(菜单)路由
* @param {*} menuList 菜单列表
* @param {*} routes 递归创建的动态(菜单)路由
*/
function addDynamicRoutes (menuList = [], routes = []) {
var temp = []
for (var i = 0; i < menuList.length; i++) {
  if (menuList[i].children && menuList[i].children.length >= 1) {
    temp = temp.concat(menuList[i].children)
  } else if (menuList[i].menuUrl && /\S/.test(menuList[i].menuUrl)) {
      menuList[i].menuUrl = menuList[i].menuUrl.replace(/^\//, '')
      // 创建路由配置
      var route = {
        path: menuList[i].menuUrl,
        component: null,
        name: menuList[i].menuName
      }
      let path = getIFrameUrl(menuList[i].menuUrl)
      if (path) {
        // 如果是嵌套页面, 通过iframe展示
        route['path'] = path
        route['component'] = resolve => require([`@/views/IFrame/IFrame`], resolve)
      } else {
      try {
         // 根据菜单URL动态加载vue组件，这里要求vue组件须按照url路径存储
         // menuUrl="sys/user"，则组件路径应是"@/views/sys/user.vue",否则组件加载不到
        let array = menuList[i].menuUrl.split('/')
        let menuUrl = array[0].substring(0,1).toUpperCase()+array[0].substring(1) + '/' + array[1].substring(0,1).toUpperCase()+array[1]  .substring(1)
        route['component'] = resolve => require([`@/views/${menuUrl}`], resolve)
      } catch (e) {}
    }
    routes.push(route)
  }
}
if (temp.length >= 1) {
  addDynamicRoutes(temp, routes)
} else {
  //  console.log('动态路由加载...')
  //  console.log(routes)
  //  console.log('动态路由加载完成.')
}
return routes
}

// 移动端菜单和路由
function addMobileMenuAndRoutes(userName, to, from){
  api.menu.findNavTree({"authType":1,"userName":userName}).then(res=>{
    res.authorityList.forEach(item=>{
      // console.log(item)
      if(item.menuName=='我的客户'){
        // console.log(item.children)
      }
    })
  })
}

export default router
